package com.sxtbbs.filter;

import java.io.UnsupportedEncodingException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * 使用装饰者模式对request对象进行处理
 * 作用：对于get请求参数进行处理，保证不乱码
 * 原理：HttpServletRequestWrapper类是HttpServletRequst接口的包装类，通过重写类的方法对HttpServletRequest对象进行增强
 * 使用：
 * 		HttpServletRequest request;
 * 		request = new GetRequest(request, charset);
 * @author lovemanai
 *
 */
public class GetRequest extends HttpServletRequestWrapper{

	private HttpServletRequest request;//原始请求对象
	private String charset;//字符编码
	
	public GetRequest(HttpServletRequest request, String charset) {
		super(request); 
		this.request = request;
		this.charset = charset;
	}

	
	/**
	 * 将接收的普通参数转码后返回
	 * @param name 参数名
	 * @return 转码后的参数值
	 */
	@Override
	public String getParameter(String name) {
		String value = request.getParameter(name);//将参数以ISO-8859-1（默认编码）的形式接收过来
		if(value == null) return value; //参数值为null直接返回
		try {
			//将参数处理之后返回
			return new String(value.getBytes(), charset);//????莫名不能指定起始编码为ISO-8859-1????
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 将接收的Map参数转码后返回
	 * @return 转码后的Map
	 */
	@Override
	public Map<String, String[]> getParameterMap() {
		Map<String, String[]> map = request.getParameterMap();
		if(map == null) return map;
		for(String key : map.keySet()) {
			String[] keyValues = map.get(key);
			for(int i = 0; i < keyValues.length; i++) {
				try {
					keyValues[i] = new String(keyValues[i].getBytes(), charset);
				} catch (UnsupportedEncodingException e) {
					throw new RuntimeException(e);
				}
			}
			map.put(key, keyValues);
		}
		
		return map;
	}
	
	
}
